<template>
  <div class="swiper-management">
    <!-- 首页轮播图管理 -->
    <h2>首页轮播图管理</h2>
    <el-row :gutter="20" class="mb-4">
      <el-col v-for="item in swiperArray" :key="item.id" :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="swiper-card">
          <img :src="item.img" class="swiper-image" alt="轮播图" />
          <div class="card-footer">
            <div class="swiper-caption">{{ item.text }}</div>
            <el-button type="primary" size="small" @click="showDialog(item.id, 'index')">
              <img src="../../assets//icons/edit.svg" alt="icon"
                style="width: 16px; height: 16px; margin-right: 8px;" />
              编辑
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 预征班轮播图管理 -->
    <h2>预征班轮播图管理</h2>

    <el-row :gutter="20" class="mb-4">
      <el-col v-for="item in PPTSwiperArray" :key="item.id" :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="swiper-card">
          <img :src="item.img" class="swiper-image" alt="轮播图" />
          <div class="card-footer">
            <div class="swiper-caption">{{ item.text }}</div>
            <el-button type="primary" size="small" @click="showDialog(item.id, 'ppt')">
              <img src="../../assets//icons/edit.svg" alt="icon"
                style="width: 16px; height: 16px; margin-right: 8px;" />
              编辑
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>


    <!-- 通用编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="`编辑${editType === 'index' ? '首页' : '预征班'}轮播图`" width="40%"
      @close="handleClose">
      <el-form label-width="80px">
        <el-form-item label="图片">
          <el-upload class="avatar-uploader" action="/api/admin/common/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="描述文字">
          <el-input v-model="caption" type="textarea" :rows="4" placeholder="请输入图片描述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateInfo">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue"
import axios from 'axios'
import { onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { getSwiper } from "@/api/Mmp/swiper"

const swiperArray = ref([])
const PPTSwiperArray = ref([])
const dialogVisible = ref(false)

const editType = ref('index') // 当前编辑类型：index/ppt
const currentId = ref("")
const caption = ref("")
const imageUrl = ref('')

// 获取轮播图数据
const fetchSwipers = async (type: string) => {
  const url = type === 'index'
    ? "/admin/mp/indexImg"
    : "/admin/mp/ppt-swiper"

  try {
    const response = await getSwiper(url)
    return response.data
  } catch (error) {
    ElMessage.error('数据加载失败')
    return []
  }
}

// 初始化数据
onMounted(async () => {
  swiperArray.value = await fetchSwipers('index')
  PPTSwiperArray.value = await fetchSwipers('ppt')
})

// 显示编辑弹窗
const showDialog = async (id: string, type: string) => {
  dialogVisible.value = true
  editType.value = type
  currentId.value = id

  try {
    const url = type === 'index'
      ? `/api/admin/mp/indexImg/${id}`
      : `/api/admin/mp/ppt-swiper/${id}`

    const response = await axios.get(url)
    imageUrl.value = response.data.data.img
    caption.value = response.data.data.text
  } catch (error) {
    ElMessage.error('数据加载失败')
    dialogVisible.value = false
  }
}

// 更新轮播图信息
const updateInfo = async () => {
  try {
    const url = editType.value === 'index'
      ? "/api/admin/mp/indexImg"
      : "/api/admin/mp/ppt-swiper"

    const payload = {
      id: currentId.value,
      img: imageUrl.value,
      text: caption.value
    }

    await axios.put(url, payload)

    if (editType.value === 'index') {
      swiperArray.value = await fetchSwipers('index')
    } else {
      PPTSwiperArray.value = await fetchSwipers('ppt')
    }

    dialogVisible.value = false
    ElMessage.success('修改成功')
  } catch (error) {
    ElMessage.error('修改失败')
  }
}

// 图片上传处理
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.code === 1) {
    imageUrl.value = response.data
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('图片必须为 JPG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 关闭弹窗重置数据
const handleClose = () => {
  imageUrl.value = ''
  caption.value = ''
  currentId.value = ''
  editType.value = 'index'
}
</script>
<style scoped>
.swiper-management {
  padding: 20px;
}

.swiper-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.swiper-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.swiper-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 4px;
}

.card-footer {
  padding: 15px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.swiper-caption {
  flex: 1;
  margin-right: 10px;
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.avatar-uploader {
  width: 100%;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100%;
  height: 200px;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 100%;
  height: 200px;
  object-fit: contain;
  display: block;
}
</style>
